package xyz.labmem.base.core.tool

import com.fasterxml.jackson.core.JsonProcessingException

/**
 * Jackson 工具
 * @Author lty
 * @Date 2021/12/14 15:24
 */

private val Jackson = JacksonObjectMapper().serializingObjectMapper()

/**
 * 对象转json字符串
 *
 * @param obj 对象
 * @return json
 * @throws JsonProcessingException
 */
fun Any.toJsonStr(): String? {
    return try {
        Jackson.writerWithDefaultPrettyPrinter()
            .writeValueAsString(this)
    } catch (e: JsonProcessingException) {
        e.printStackTrace()
        null
    }
}

/**
 * json字符串转回对象
 *
 * @param json   json
 * @param eClass 对象Class
 * @return 对象实体
 * @throws JsonProcessingException
 */
fun <E> String.jsonToObject(eClass: Class<E>): E? {
    return try {
        Jackson.readValue(this, eClass)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}